//导入题库的数据模型
const { T_exam_paper, T_exam_paper_to_question } = require('../models/t_exam_paper')
const { T_exam_label } = require('../models/t_exam_label')
const { T_exam_question } = require('../models/t_exam_question')
const { T_subjects } = require('../models/t_exam_subjects')
const { Op } = require('sequelize')
//获取信息的业务处理
exports.getAll_desc_paper = async (req, res) => {
    try {
        const ACSId = req.query.ASCId
        const paperType = req.query.paperType
        const submes = await T_exam_paper.findAll({
            where: {
                t_user_and_a_c_s_id: ACSId,
                type_paper: paperType
            }
        });
        res.json({
            "code": 200,
            "mag": "查询全部成功",
            "data": submes
        })
    } catch (error) {
        console.log(error);
        res.json({
            "code": 500,
            "msg": "查询全部失败",
        })
    }
}


//查询一张试卷具体信息
exports.getA_desc_paper = async (req, res) => {
    try {
        const paperId = req.query.Id
        const papermes = await T_exam_paper.findOne({
            where: {
                id: paperId
            }
        });
        res.json({
            "code": 200,
            "mag": "查询全部成功",
            "data": papermes
        })
    } catch (error) {
        res.json({
            "code": 500,
            "msg": "查询全部失败",
        })
    }
}


//插入试卷
exports.create_desc_paper = async (req, res) => {
    const body = req.body;


    try {
        const t_subject = await T_exam_paper.create({
            id: null,
            // temScore: body.temScore,
            // class: body.class,
            paper_name: body.paperName,
            // term: body.term,
            // academy_yaer: body.academyYaer,
            academy: body.academy,
            format: body.format,
            type_paper: body.typePaper,
            t_user_and_a_c_s_id: body.ACSId,
            // score: body.score,
            question_count: body.questionCount,
            suggest_time: body.suggestTime
        });

        res.json({
            "code": 200,
            "msg": '创建成功',
            "data": t_subject,
        });
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};

//更新试卷描述信息
exports.updatet_desc_paper = async (req, res) => {
    const id = req.query.id
    // 获取各种信息
    const body = req.body
    try {

        const [updateRows] = await T_exam_paper.update(
            {
                temScore: body.temScore,
                class: body.class,
                paper_name: body.paperName,
                term: body.term,
                academy_yaer: body.academyYaer,
                academy: body.academy,
                format: body.format,
                type_paper: body.typePaper,
                t_user_and_a_c_s_id: body.ACSId,
                score: body.score,
                question_count: body.questionCount,
                suggest_time: body.suggestTime
            },
            { where: { id } },
        );

        res.json({
            "code": 200,
            "msg": "更新成功" + updateRows,
        });

    }
    catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        })
    }
}

//删除试卷  题目也会一起删除
exports.delete_desc_paper = async (req, res) => {
    const id = req.query.id;
    try {

        const deletetopic = await T_exam_paper_to_question.destroy({
            where: {
                paper_id: id
            }
        })
        const deletedRows = await T_exam_paper.destroy({
            where: { id },
        });
        //删除成功则返回该试卷的题目数量
        if (deletedRows > 0) {
            res.json({
                "code": 200,
                "msg": deletetopic,
            });
        } else {
            res.json({
                "code": 404,
                "msg": `不存在该试卷`,
            });
        }
    } catch (error) {
        res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};



//后面是试卷的题目查询
//需要通过查询 T_exam_paper_to_question 的question_id  再在question表里面找题目信息
// const { T_exam_question } = require('../models/t_exam_question')


//查询需要paper的id
//查询试卷的题目信息
const { Sequelize } = require('sequelize')

exports.getAll_topic_paper = async (req, res) => {
    try {
        const id = req.query.paperId

        // 查找指定ID的试卷
        const paper = await T_exam_paper.findByPk(id);
        if (!paper) {
            res.json({
                code: 400,
                msg: '试卷不存在',
            });
            return;
        }
        // 查找试卷包含的题目
        const paperToQuestions = await T_exam_paper_to_question.findAll({
            where: { paper_id: id },
            include: [{
                model: T_exam_question
            }],
            order: [
                ['question_num', 'ASC']
            ]
        });
        if (paperToQuestions.length === 0) {
            res.json({
                code: 400,
                msg: '试卷中没有题目',
            });
            return;
        }


        // 构造题目信息对象，按类型分类
        const questionInfoByType = [];
        paperToQuestions.forEach((paperToQuestion) => {
            const question = paperToQuestion.T_exam_question;

            questionInfoByType.push({
                realId: paperToQuestion.id,
                id: question.id,
                labelId: question.label_id,
                ACSId: question.t_user_and_a_c_s_id,
                questionContent: question.questionContent,
                options: question.options,
                answer: question.answer,
                type: question.type,
                score: question.score,
                difficulty: question.difficulty,
                createdAt: question.createdAt,
                updatedAt: question.updatedAt
            });
        });


        res.json({
            "code": 200,
            "mag": "查询全部成功",
            "data": questionInfoByType
        })
    } catch (error) {
        console.log(error)
        res.json({
            "code": 500,
            "msg": error,
        })
    }
}





//为试卷添加题目
exports.create_topic_paper = async (req, res) => {
    //需要两个参数  一个是试卷id  一个是问题id
    const data = req.body.data;
    const arr = [];
    console.log(data);
    console.log(typeof (data));
    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++) {
            const temp = {
                id: null,
                paper_id: data[i].paperId,
                question_id: data[i].questionId,
                question_num: null,
            }

            //判断数据是否存在
            try {
                const record = await T_exam_paper_to_question.findOne({
                    where: {
                        [Op.and]: [
                            { paper_id: { [Op.eq]: data[i].paperId } },
                            { question_id: { [Op.eq]: data[i].questionId } },
                        ]
                    }
                });

                if (!record) {
                    arr.push(temp);
                }
            } catch (error) {
                return res.json({
                    code: 500,
                    msg: error.message,
                });
            }

        }
    } else if (typeof data === 'undefined') {

        res.json({
            "code": 500,
            "msg": "未传递数组对象",
        });
    }


    try {
        const t_subject = await T_exam_paper_to_question.bulkCreate(
            arr
        );

        res.json({
            "code": 200,
            "msg": '创建成功',
            "data": t_subject,
        });
    } catch (error) {
        return res.json({
            "code": 500,
            "msg": error.message,
        });
    }
};


//删除试卷的题目
exports.delete_topic_paper = async (req, res) => {
    //需要两个参数  一个是试卷id  一个是问题id
    const data = req.body.data;
    console.log(data);
    let rows = 0
    if (Array.isArray(data)) {
        for (let i = 0; i < data.length; i++) {

            try {
                const deletedRows = await T_exam_paper_to_question.destroy({
                    where: {
                        [Op.and]: [
                            { paper_id: { [Op.eq]: data[i].paperId } },
                            { question_id: { [Op.eq]: data[i].questionId } },
                        ]
                    }
                })
                rows += deletedRows
            } catch (error) {
                res.json({
                    code: 500,
                    msg: error.message,
                });
            }

        }

        if (rows > 0) {
            res.json({
                "code": 200,
                "msg": "删除成功" + rows + "条数据",
            });
        } else {
            res.json({
                "code": 200,
                "msg": "未有能被删除的数据",
            })
        }

    } else if (typeof data === 'undefined') {

        res.json({
            "code": 500,
            "msg": "未传递数组对象",
        });
    }
};

//规格查询试卷题目
const { T_question_score } = require('../models/T_question_score')
//规格查询试卷题目
exports.getPaperQuestionsByType = async (req, res) => {
    const { id, ACSId } = req.query;

    if (!id || !ACSId) {
        return json.res({
            code: 500,
            error: "未正确传值"
        })
    }

    const quetionScore = await T_question_score.findOne({
        where: {
            t_user_and_a_c_s_id: ACSId
        }
    })
    console.log(quetionScore);


    function addLettersToOptions(options) {
        let n = 0
        let stringlenth = 0
        for (let i = 0; i < options.length; i++) {
            n += options[i].length
            if ((i + 1) % 2 === 1) {
                if (stringlenth < options[i].length) {
                    stringlenth = options[i].length
                }
            }
        }

        // const updatedOptions = {};
        for (let i = 0; i < options.length; i++) {


            // 生成字母键（A、B、C...），其中65是字母A在ASCII中的编码
            const letterKey = String.fromCharCode(65 + i);
            // 拼接字母到原始值上

            if (n <= 24) {
                options[i] = letterKey + "." + options[i].trim() + '    ';
                if ((i + 1) % 4 === 0) {
                    options[i] += '\n'
                }
            } else if (n < 48) {
                options[i] = letterKey + "." + options[i].trim() + '    ';
                if ((i + 1) % 2 === 1) {

                    console.log("xuyao", stringlenth - options[i].length + 6);
                    const addBlack = stringlenth - options[i].length + 6;
                    for (let j = 0; j < addBlack * 2; j++) {
                        options[i] = options[i] + ' '
                    }

                }


                if ((i + 1) % 2 === 0) {
                    options[i] += '\n'
                }
            } else if (n >= 48) {
                options[i] = letterKey + "." + options[i].trim() + '\n';
            }

        }
        return options;
    }
    try {
        // 查找指定ID的试卷
        const paper = await T_exam_paper.findByPk(id);
        if (!paper) {
            res.json({
                code: 400,
                msg: '试卷不存在',
            });
            return;
        }
        // 查找试卷包含的题目
        const paperToQuestions = await T_exam_paper_to_question.findAll({
            where: { paper_id: id },
            include: [{
                model: T_exam_question
            }],
            order: [
                ['question_num', 'ASC']
            ]
        });
        if (paperToQuestions.length === 0) {
            res.json({
                code: 400,
                msg: '试卷中没有题目',
            });
            return;
        }

        // 构造试卷信息对象
        const paperInfo = {
            paperId: paper.id,
            paperName: paper.paper_name,
            term: paper.term,
            academyYear: paper.academy_yaer,
            academy: paper.academy,
            format: paper.format,
            typePaper: paper.type_paper,
            ACSId: paper.t_user_and_a_c_s_id,
            score: paper.score,
            temScore: paper.temScore,
            class: paper.class,
            questionCount: paper.question_count,
            suggestTime: paper.suggest_time,
        };


        // 构造题目信息对象，按类型分类
        const questionInfoByType = {};
        const questionInfo = {}

        paperToQuestions.forEach((paperToQuestion) => {
            let score = 0
            const question = paperToQuestion.T_exam_question;
            if (!questionInfoByType[question.type]) {
                questionInfoByType[question.type] = [];
            }

            if (!questionInfo[question.type]) {
                questionInfo[question.type] = { num: 0, score: 0 };
            }



            if (question.type === "单项选择题") {
                score = quetionScore.oneChoiceQuestions
            } else if (question.type === "多项选择题") {
                score = quetionScore.multipleChoiceQuestions
            } else if (question.type === "判断题") {
                score = quetionScore.judgeQuestions
            } else if (question.type === "填空题") {
                score = quetionScore.fillBlankQuestions
            } else {
                score = 15
            }
            // question.score = score

            questionInfo[question.type].num++
            questionInfo[question.type].score += score

            questionInfoByType[question.type].push({
                id: question.id,
                labelId: question.label_id,
                ACSId: question.t_user_and_a_c_s_id,
                questionContent: question.questionContent,
                options: addLettersToOptions(question.options),
                answer: question.answer,
                type: question.type,
                score: question.score,
                difficulty: question.difficulty,
                createdAt: question.createdAt,
                updatedAt: question.updatedAt
            });

        });
        console.log(questionInfoByType);
        const data = {
            paper: paperInfo,
            questionInfoByType: Object.keys(questionInfoByType).map(type => ({
                type,
                num: questionInfo[type].num,
                score: questionInfo[type].score,
                questions: questionInfoByType[type].map(question => ({
                    questionContent: question.questionContent,
                    options: question.options,
                })),
            })),
        };


        res.json({
            code: 200,
            msg: '查询成功',
            data: data
        });
    } catch (error) {
        res.json({
            code: 500,
            msg: error.message,
        });
    }
};

exports.exchange_topic_paper = async (req, res) => {
    try {
        const id = req.query.id
        const paperId = req.query.paperId
        const questionId = req.query.questionId
        const paperQuestion = await T_exam_paper_to_question.findAll({
            where: {
                paper_id: paperId,
                question_id: questionId
            }
        })
        // console.log("hhhh", paperQuestion);
        if (paperQuestion.length > 0) {
            return res.json({
                "code": 200,
                "mes": "重复插入题目"
            })
        }

        T_exam_paper_to_question.update({
            question_id: questionId
        },
            {
                where: {
                    id: id,
                    paper_id: paperId
                }
            })


        res.json({
            "code": 200,
            "mes": "更新成功"
        })
    } catch (error) {
        res.json({
            "code": 200,
            "mes": error.msg
        })
    }

}